import { Injectable } from '@nestjs/common';
import * as axios from "axios"
import { writeFileSync } from 'fs';
import { stringify } from 'qs';
import { CacheService } from 'src/cache/cache.service';
@Injectable()
export class DingtalkService {
    constructor(
        private readonly cache: CacheService
    ) { }

    private readonly fetch = axios.default.create({
        baseURL: "https://oapi.dingtalk.com/"
    })

    private async query<T = any>(url: string, data: any, method: "get" | "post" = "post") {
        let err: any;
        const result: T = await this.fetch<T>({
            method,
            url,
            params: {
                access_token: await this.getToken()
            },
            data: data
        }).then((e) => {
            return e.data
        }).catch(e => {
            err = e;
            return null;
        })
        if (!!err) throw err;
        return result;
    }

    private async getToken() {
        return await this.cache.has(async () => {
            console.log("------------------------------------------------")
            console.log("getToken")
            console.log("------------------------------------------------")
            return await this.fetch.get("gettoken", {
                params: {
                    appkey: process.env.AppKey,
                    appsecret: process.env.AppSecret
                }
            }).then(e => e.data.access_token).catch(e => {
                console.log(e);
                return null
            })
        }, "assets_token");
    }

    public async saveAvatar(url: string, path: string) {
        console.log(url, path)
        await axios.default.get(url, {
            responseType: 'arraybuffer', // 特别注意，需要加上此参数
        }).then(e => {
            writeFileSync(path, e.data)
        })
    }

    /**
     * 通过手机号获取员工信息
     * @param mobile 手机号
     */
    getByMobile(mobile: string) {
        return this.query("topapi/v2/user/getbymobile", { mobile })
    }

    /**
     * 获取考勤列表
     * @param userIdList 用户id列表
     * @param workDateFrom 开始时间 YYYY-MM-DD hh:mm:ss
     * @param workDateTo 结束时间
     * @param page  页数
     * @param limit 限制
     * @returns 
     */
    attendanceList(
        userIdList: string[],
        workDateFrom: string,
        workDateTo: string,
        page = 1,
        limit = 50
    ) {
        return this.query("attendance/listRecord", {
            userIdList,
            workDateFrom,
            workDateTo,
            limit,
            offset: (page - 1) * limit
        })
    }

    /**
     * 获取用户id列表
     */
    userListid() {
        return this.query("topapi/user/listid", { dept_id: 1 })
    }

    /**
     * @returns 查询用户详情
     */
    usetGet(userid: string) {
        return this.query("topapi/v2/user/get", { userid })
    }



}
